﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Bling.DSL;
using Bling.WPF;
using Bling.Animation;
using Bling.Shaders;
using Bling.Util;
namespace Bling.Tutorial {
  public class Diffusion : Canvas, CanStart {
    readonly BackgroundTimer Timer;
    public Diffusion() {
      CanvasBl MainCanvas = this;
      var canvasA = new CanvasBl(MainCanvas) {
        Size = MainCanvas.Size / 2d,
        LeftBottom = new PointBl(0,MainCanvas.Height), 
        ClipToBounds = true,
      };
      var thumbA = new ThumbBl(canvasA) {
        Background = Brushes.Red, CanDrag = true,
        CenterPosition = canvasA.CenterSize,
      };
      new RectangleBl(canvasA) {
        Stroke = { Brush = Brushes.Black, Thickness = 1 },
        Size = canvasA.Size, LeftTop = new Point(0,0),
      };

      var canvasB = new CanvasBl(MainCanvas) {
        Size = canvasA.Size,
        LeftBottom = canvasA.LeftTop,
        Background = Brushes.Transparent,
      };
      RenderTargetBitmap bitmapA = null; // new RenderTargetBitmap(500, 500, 96, 96, PixelFormats.Pbgra32);
      RenderTargetBitmap bitmapB = null; // new RenderTargetBitmap(500, 500, 96, 96, PixelFormats.Pbgra32);


      BrushBl brushA = new VisualBrush { Visual = canvasA };
      BrushBl brushB = new VisualBrush { Visual = canvasB };

      Timer = new BackgroundTimer(this.Dispatcher, 10, () => { }, () => {
        ImageBl imageA = null;
        ImageBl imageB = null;
        ImageBrush brushC = new ImageBrush();
        if (bitmapA == null) {
          bitmapA = new RenderTargetBitmap((int)(canvasA.Width.Ceiling.CurrentValue), (int)(canvasA.Height.Ceiling.CurrentValue), 96, 96, PixelFormats.Pbgra32);
          bitmapB = new RenderTargetBitmap((int)(canvasA.Width.Ceiling.CurrentValue), (int)(canvasA.Height.Ceiling.CurrentValue), 96, 96, PixelFormats.Pbgra32);
          imageB = new ImageBl(MainCanvas) {
            Size = canvasA.Size,
            LeftTop = canvasB.RightTop,
            Source = bitmapB,
          };
          imageA = new ImageBl(MainCanvas) {
            Size = canvasA.Size,
            LeftTop = imageB.LeftBottom,
            Source = bitmapB,
          };

          brushC.ImageSource = bitmapB;
          canvasB.Effect.Custom = (input, uv) => {
            return brushA[uv].Max(brushC.Bl()[uv]);
          };
        }
        bitmapA.Clear();
        bitmapA.Render(canvasB);
        {
          var temp = bitmapA;
          bitmapA = bitmapB;
          bitmapB = temp;
          brushC.ImageSource = bitmapB;



        }



      });

    }
    public void Start() { Timer.Start(); }
    public void Stop() { Timer.Stop(); }
  }

}